#!/bin/bash

# JPY汇率检测系统更新脚本

set -e

echo "🔄 开始更新JPY汇率检测系统..."

PROJECT_DIR="/home/pi/jpy2-cny"
SERVICE_USER="pi"

# 检查项目目录是否存在
if [ ! -d "$PROJECT_DIR" ]; then
    echo "❌ 错误: 项目目录不存在，请先运行安装脚本"
    exit 1
fi

# 备份当前配置
echo "💾 备份当前配置..."
BACKUP_DIR="/tmp/jpy-rate-backup-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR"

# 备份重要文件
cp "$PROJECT_DIR/.env" "$BACKUP_DIR/" 2>/dev/null || true
cp "$PROJECT_DIR/backend/policies/PolicyProfile.json" "$BACKUP_DIR/" 2>/dev/null || true
cp "$PROJECT_DIR/jpy_rates.db" "$BACKUP_DIR/" 2>/dev/null || true

echo "📁 配置备份到: $BACKUP_DIR"

# 停止服务
echo "⏹️  停止服务..."
sudo systemctl stop jpy-rate.service
sudo systemctl stop jpy-rate.timer

# 更新项目文件
echo "📋 更新项目文件..."
cd "$PROJECT_DIR"
sudo -u $SERVICE_USER git pull origin master 2>/dev/null || {
    echo "⚠️  Git拉取失败，手动复制文件..."
    # 如果git不可用，手动复制文件
    sudo cp -r /tmp/jpy2-cny/* "$PROJECT_DIR/" 2>/dev/null || true
}

# 更新依赖
echo "📦 更新Python依赖..."
sudo -u $SERVICE_USER ./venv/bin/pip install --upgrade pip
sudo -u $SERVICE_USER ./venv/bin/pip install -r requirements.txt

# 恢复配置
echo "🔄 恢复配置..."
cp "$BACKUP_DIR/.env" "$PROJECT_DIR/" 2>/dev/null || true
cp "$BACKUP_DIR/PolicyProfile.json" "$PROJECT_DIR/backend/policies/" 2>/dev/null || true
cp "$BACKUP_DIR/jpy_rates.db" "$PROJECT_DIR/" 2>/dev/null || true

# 重启服务
echo "🚀 重启服务..."
sudo systemctl start jpy-rate.service
sudo systemctl start jpy-rate.timer

# 检查服务状态
echo "📊 检查服务状态..."
sleep 5
sudo systemctl status jpy-rate.service --no-pager

echo ""
echo "✅ 更新完成！"
echo ""
echo "📁 配置备份位置: $BACKUP_DIR"
echo "🌐 访问地址: http://$(hostname -I | awk '{print $1}'):8000"
